<template>
  <div class="draw-tools">
    <!-- 绘图工具栏 -->
    <div class="tool-section">
      <h3>绘图工具</h3>
      
      <!-- 图形绘制 -->
      <div class="tool-item">
        <el-select
          v-model="selectedShape"
          placeholder="请选择绘制图形"
          style="width: 120px"
          :disabled="!canSelectShape"
          @change="onShapeSelected"
        >
          <el-option
            v-for="option in shapeOptions"
            :key="option.type"
            :label="option.name"
            :value="option.type"
          >
            <span>{{ option.name }}</span>
          </el-option>
        </el-select>
        
        <el-button 
          @click="startDrawShape" 
          :disabled="!canDraw"
          :type="isDrawing ? 'primary' : 'default'"
        >
          {{ isDrawing ? '绘制中...' : '开始绘制' }}
        </el-button>
      </div>
      
      <!-- 图标绘制 -->
      <div class="tool-item">
        <el-select
          v-model="selectedIcon"
          placeholder="请选择添加图标"
          style="width: 120px"
          :disabled="!canSelectShape"
        >
          <el-option
            v-for="option in iconOptions"
            :key="option.type"
            :label="option.name"
            :value="option.type"
          >
            <span>{{ option.name }}</span>
          </el-option>
        </el-select>
        
        <el-button 
          @click="startDrawIcon" 
          :disabled="!isMapReady || !is2D || !selectedIcon"
        >
          添加图标
        </el-button>
      </div>
      
      <!-- 删除状态切换 -->
      <div class="tool-item switch-item">
        <el-switch 
          :model-value="isDelete" 
          @update:model-value="toggleDelete" 
          :disabled="!isMapReady || !is2D" 
        />
        <span>删除状态（鼠标左键单击删除元素）</span>
      </div>
      
      <!-- 编辑状态切换 -->
      <div class="tool-item switch-item">
        <el-switch 
          :model-value="isModify" 
          @update:model-value="toggleModify" 
          :disabled="!isMapReady || !is2D" 
        />
        <span>编辑状态</span>
      </div>
      
      <!-- 图标调整 -->
      <div class="tool-item">
        <el-button :disabled="!isMapReady || !is2D" @click="adjustIconSize(0.02)">
          增大图标
        </el-button>
        <el-button :disabled="!isMapReady || !is2D" @click="adjustIconSize(-0.02)">
          减小图标
        </el-button>
      </div>
      
      <!-- 保存绘制 -->
      <div class="tool-item">
        <el-button type="success" @click="saveDrawings" :disabled="!isMapReady || !is2D">
          保存绘制
        </el-button>
        <el-button type="warning" @click="loadDrawings" :disabled="!isMapReady || !is2D">
          加载绘制
        </el-button>
      </div>

      <!-- 调试区域 -->
      <div v-if="false" class="debug-info">
        <h4>调试信息</h4>
        <p>地图就绪状态 isMapReady: {{ isMapReady }}</p>
        <p>计算就绪状态 isMapReady2: {{ isMapReady2 }}</p>
        <p>是否可选择形状: {{ canSelectShape }}</p>
        <p>是否2D: {{ is2D }}</p>
        <p>当前选择的形状: {{ selectedShape }}</p>
        <p>是否可以绘制: {{ canDraw }}</p>
        <hr>
        <h5>Map对象信息:</h5>
        <p>Map存在: {{ mapDebug.mapExists }}</p>
        <p>Map有值: {{ mapDebug.mapHasValue }}</p>
        <p>Map类型: {{ mapDebug.mapType }}</p>
        <hr>
        <h5>Source对象信息:</h5>
        <p>Source存在: {{ sourceDebug.sourceExists }}</p>
        <p>Source有值: {{ sourceDebug.sourceHasValue }}</p>
        <p>Source类型: {{ sourceDebug.sourceType }}</p>
        <hr>
        <h5>下拉菜单选项:</h5>
        <p>可用形状: {{ shapeOptions.map(o => o.name).join(', ') }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount, nextTick, computed } from 'vue';
import { useDraw } from '../hooks/useDraw';
import { ElMessage } from 'element-plus';
import { useDrawStore } from '@/stores/modules/draw';

// 接收props
const props = defineProps({
  map: {
    type: Object,
    required: true
  },
  sourceFeatures: {
    type: Object,
    required: true
  },
  is2D: {
    type: Boolean,
    default: true
  }
});

// 使用draw store
const drawStore = useDrawStore();

// 响应式状态 - 使用store中的状态
const isMapReady = computed(() => drawStore.isMapReady);
const isDrawing = computed(() => drawStore.isDrawing);
const isDelete = computed(() => drawStore.isDelete);
const isModify = computed(() => drawStore.isModify);
const selectedShape = computed({
  get: () => drawStore.selectedShape,
  set: (val) => drawStore.setSelectedShape(val)
});
const selectedIcon = computed({
  get: () => drawStore.selectedIcon,
  set: (val) => drawStore.setSelectedIcon(val)
});
const scale = computed(() => drawStore.scale);
const shapeOptions = computed(() => drawStore.shapeOptions);
const iconOptions = computed(() => drawStore.iconOptions);
const canSelectShape = computed(() => drawStore.canSelectShape);
const canDraw = computed(() => drawStore.canDraw);

// 本地引用
const drawHook = ref(null);

// 调试状态
const mapDebug = computed(() => {
  return {
    mapExists: props.map ? 'yes' : 'no',
    mapHasValue: props.map ? 'yes' : 'no', 
    mapType: props.map ? typeof props.map : 'unknown',
    mapValue: props.map
  };
});

const sourceDebug = computed(() => {
  return {
    sourceExists: props.sourceFeatures ? 'yes' : 'no',
    sourceHasValue: props.sourceFeatures ? 'yes' : 'no',
    sourceType: props.sourceFeatures ? typeof props.sourceFeatures : 'unknown'
  };
});

// 检查地图和要素源是否可用
const isMapReady2 = computed(() => {
  const hasMap = !!props.map;
  const hasSource = !!props.sourceFeatures;
  console.log(`地图可用状态检查: hasMap=${hasMap}, hasSource=${hasSource}, is2D=${props.is2D}`);
  return hasMap && hasSource;
});

// 监听3D/2D模式变化
watch(() => props.is2D, (newValue) => {
  console.log('2D/3D模式已切换:', newValue);
  
  if (!newValue) {
    // 如果切换到3D模式，清理所有交互
    cleanupInteractions();
  } else if (drawHook.value) {
    // 如果切换回2D模式，并且钩子已初始化，重新初始化交互
    try {
      drawHook.value.initInteractions();
    } catch (e) {
      console.error('重新初始化交互失败:', e);
    }
  }
}, { immediate: true });

// 添加监听drawHook的isDrawing变化
watch(() => drawHook.value?.isDrawing.value, (newVal) => {
  if (newVal !== undefined) {
    drawStore.setDrawing(newVal);
    console.log('绘图状态更新:', newVal ? '绘制中' : '未绘制');
  }
}, { immediate: true });

// 检查map和sourceFeatures对象
function checkMapAndSource() {
  const hasMap = props.map;
  const hasSource = props.sourceFeatures;
  
  if (!hasMap) {
    console.warn('地图对象不可用');
  }
  
  if (!hasSource) {
    console.warn('要素源不可用');
  }
  
  return hasMap && hasSource;
}

// 清理所有交互
function cleanupInteractions() {
  drawStore.clearInteractions();
}

// 尝试初始化绘图功能
function initDraw() {
  if (!props.is2D) {
    console.warn('当前处于3D模式，不初始化绘图功能');
    return;
  }
  
  try {
    console.log('开始初始化绘图功能');
    
    // 直接引用map和sourceFeatures
    console.log('初始化useDraw时的参数:', {
      'map对象': props.map,
      'map类型': typeof props.map,
      'sourceFeatures对象': props.sourceFeatures,
      'sourceFeatures类型': typeof props.sourceFeatures
    });
    
    // 验证map和sourceFeatures对象
    if (!checkMapAndSource()) {
      console.warn('地图对象或要素源不可用，使用基本UI模式');
      drawStore.setMapReady(true); // 允许基本UI可用
      return;
    }
    
    // 使用钩子创建绘图功能 - 为useDraw创建包装对象
    drawHook.value = useDraw({ value: props.map }, { value: props.sourceFeatures });
    
    // 将钩子设置到store中
    drawStore.setDrawHook(drawHook.value);
    
    // 设置就绪状态
    drawStore.setMapReady(true);
    console.log('绘图功能初始化成功');
  } catch (error) {
    console.error('初始化绘图功能出错:', error);
    ElMessage.error('绘图工具初始化失败，将使用基本UI');
    // 即使出错也保持基本UI可用
    drawStore.setMapReady(true);
  }
}

// 开始绘制形状
function startDrawShape() {
  console.log('开始绘制按钮被点击');
  
  // 记录当前状态
  console.log('当前状态:', {
    map: props.map ? '存在' : '不存在',
    sourceFeatures: props.sourceFeatures ? '存在' : '不存在',
    is2D: props.is2D,
    selectedShape: selectedShape.value,
    drawHook: drawHook.value ? '已初始化' : '未初始化'
  });
  
  // 验证必要条件
  if (!selectedShape.value) {
    console.warn('未选择形状类型');
    ElMessage.warning('请选择需要绘制的形状');
    return;
  }
  
  if (!props.map) {
    console.warn('地图对象不可用');
    ElMessage.warning('地图对象未初始化，无法绘制');
    return;
  }
  
  if (!props.sourceFeatures) {
    console.warn('要素源不可用');
    ElMessage.warning('要素数据源未初始化，无法绘制');
    return;
  }
  
  if (!props.is2D) {
    console.warn('3D模式下不支持绘制');
    ElMessage.warning('3D模式下无法使用绘图功能，请切换到2D模式');
    return;
  }
  
  // 确保绘图钩子已初始化
  if (!drawHook.value) {
    console.error('绘图钩子未初始化，尝试重新初始化');
    
    // 再次尝试初始化
    try {
      drawHook.value = useDraw({ value: props.map }, { value: props.sourceFeatures });
      drawStore.setDrawHook(drawHook.value);
      console.log('绘图钩子重新初始化成功');
    } catch (error) {
      console.error('绘图钩子初始化失败:', error);
      ElMessage.error('绘图工具初始化失败: ' + (error.message || '未知错误'));
      return;
    }
  }
  
  // 执行绘制操作
  drawStore.startDrawShape();
}

// 开始绘制图标
function startDrawIcon() {
  if (!isMapReady.value) {
    ElMessage.warning('地图未准备就绪，请稍后再试');
    return;
  }
  
  if (!selectedIcon.value) {
    ElMessage.warning('请先选择要添加的图标');
    return;
  }
  
  try {
    // 先关闭删除和编辑状态
    if (isDelete.value) {
      toggleDelete(false);
    }
    if (isModify.value) {
      toggleModify(false);
    }
    
    // 如果当前正在绘制，先清除绘制交互
    if (isDrawing.value && drawHook.value?.clearInteractions) {
      console.log('清除当前绘制交互');
      drawHook.value.clearInteractions();
    }
    
    // 开始绘制图标
    drawStore.startDrawIcon();
    
    // 添加调试日志
    console.log('组件中图标绘制已启动:', {
      '组件状态-绘制': isDrawing.value,
      '组件状态-删除': isDelete.value,
      '组件状态-编辑': isModify.value,
      'store状态-绘制': drawStore.isDrawing,
      'store状态-删除': drawStore.isDelete,
      'store状态-编辑': drawStore.isModify
    });
  } catch (error) {
    console.error('添加图标失败:', error);
    ElMessage.error('添加图标失败: ' + (error.message || '未知错误'));
  }
}

// 调整图标大小
function adjustIconSize(delta) {
  drawStore.adjustIconScale(delta);
}

// 切换删除状态
function toggleDelete(val) {
  console.log('切换删除状态:', val);
  
  try {
    // 先更新store中的状态
    drawStore.setDelete(val);
    
    // 然后调用toggle方法初始化交互
    drawStore.toggleDelete(val);
    
    // 添加调试日志
    console.log('删除状态已更新:', {
      'store中的状态': drawStore.isDelete,
      '组件中的状态': isDelete.value,
      'drawHook状态': drawHook.value?.isDelete?.value
    });
  } catch (error) {
    console.error('切换删除状态时出错:', error);
    ElMessage.error('切换删除状态失败: ' + (error.message || '未知错误'));
  }
}

// 切换编辑状态
function toggleModify(val) {
  console.log('切换编辑状态:', val);
  
  try {
    // 先更新store中的状态
    drawStore.setModify(val);
    
    // 然后调用toggle方法初始化交互
    drawStore.toggleModify(val);
    
    // 添加调试日志
    console.log('编辑状态已更新:', {
      'store中的状态': drawStore.isModify,
      '组件中的状态': isModify.value,
      'drawHook状态': drawHook.value?.isModify?.value
    });
  } catch (error) {
    console.error('切换编辑状态时出错:', error);
    ElMessage.error('切换编辑状态失败: ' + (error.message || '未知错误'));
  }
}

// 保存绘制
function saveDrawings() {
  const result = drawStore.saveDrawings();
  if (result.success) {
    ElMessage.success('绘图已保存');
  } else {
    ElMessage.error('保存失败: ' + (result.message || '未知错误'));
  }
}

// 加载绘制
function loadDrawings() {
  const result = drawStore.loadDrawings();
  if (result.success) {
    ElMessage.success(`已加载 ${result.featuresCount} 个要素`);
  } else {
    ElMessage.error('加载失败: ' + (result.message || '未知错误'));
  }
}

// 添加事件处理函数
function onShapeSelected(value) {
  console.log('形状已切换为:', value);
  ElMessage({
    message: `已选择绘制形状: ${value}`,
    type: 'success',
    duration: 1000
  });
}

// 组件挂载时初始化
onMounted(() => {
  console.log('DrawTools组件已挂载');
  
  // 打印props状态
  console.log('DrawTools组件初始状态:', {
    'map存在': !!props.map,
    'map有值': !!props.map?.value,
    'sourceFeatures存在': !!props.sourceFeatures,
    'sourceFeatures有值': !!props.sourceFeatures?.value,
    'is2D': props.is2D
  });
  
  // 如果地图和要素源都已可用，直接初始化
  if (props.map && props.sourceFeatures && props.is2D) {
    console.log('条件满足，准备初始化绘图功能');
    nextTick(() => {
      initDraw();
    });
  } else {
    console.warn('地图或数据源未就绪，稍后将通过watch初始化');
  }
});

// 监听props变化
watch([() => props.map?.value, () => props.sourceFeatures?.value], ([newMap, newSource]) => {
  console.log('地图对象或要素源已更新:', {
    'map可用': !!newMap,
    'source可用': !!newSource,
    'is2D': props.is2D,
    'isMapReady': isMapReady.value
  });
  
  // 如果地图和要素源都可用且处于2D模式，尝试初始化
  if (newMap && newSource && props.is2D && !isMapReady.value) {
    console.log('检测到地图和数据源已就绪，准备初始化绘图功能');
    nextTick(() => {
      initDraw();
    });
  }
}, { immediate: true });

// 组件卸载前清理
onBeforeUnmount(() => {
  console.log('DrawTools组件将卸载');
  cleanupInteractions();
});
</script>

<style scoped>
.draw-tools {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  width: 320px;
  max-height: 90vh;
  overflow-y: auto;
}

.tool-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #409EFF;
}

.tool-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.switch-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.switch-item span {
  font-size: 14px;
}

.debug-info {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-size: 12px;
}

.debug-info h4 {
  margin-top: 0;
  margin-bottom: 8px;
  color: #409EFF;
}

.debug-info h5 {
  margin-top: 10px;
  margin-bottom: 5px;
  color: #67c23a;
}

.debug-info p {
  margin: 3px 0;
}

.debug-info hr {
  border: 0;
  border-top: 1px dashed #dcdfe6;
  margin: 10px 0;
}
</style> 